import numpy as np
import matplotlib.pyplot as plt

def chaos_map(x, a=3.99):
    return np.mod(a * x * (1 - x), 1)

def chaos_ext(x,n):
    key = []
    for i in range(n):
        x = chaos_map(x)
        # key.append(int(x * 10000) % 256)
        key.append(x)
    return key

# 将状态值转化为二进制
def decimal_array_to_binary(decimal_array):
    binary_array = []
    for decimal in decimal_array:
        binary = ""
        while decimal != 0:
            decimal *= 2
            if decimal >= 1:
                binary += "1"
                decimal -= 1
            else:
                binary += "0"
            if len(binary) > 64:  # 设置精度为32位，防止死循环
                break
        binary_array.append(binary[8:16])
    return binary_array

def showChart(data):
    # 计算概率分布
    counts, bins = np.histogram(data, bins=256)
    probs = counts / sum(counts) * 100

    # 绘制概率分布图
    plt.bar(bins[:-1], probs, width=0.004, alpha=0.7)

    plt.ylim([0, 8.0])
    # plt.yticks([0,0.5,1.0,1.5,2.0])
    plt.yticks([0, 1, 2, 3, 4, 5, 6, 7, 8])

    plt.xlim([0, 1])
    # plt.xticks([0,25,50,75,100,125,150,175,200,225,250])
    plt.xticks([0, 0.2, 0.4, 0.6, 0.8, 1.0])

    # 添加标题和标签
    plt.title('chaos_map')
    plt.xlabel('Value')
    plt.ylabel('Probability (%)')

    # 显示图像
    plt.show()

if __name__ == '__main__':
    n = 50000
    key = []
    x = 0.12
    for i in range(n):
        x = chaos_map(x)
        # key.append(int(x * 10000) % 256)
        key.append(x)
    print(key)

    binary_array = decimal_array_to_binary(key)
    decimal_list = [int(binary, 2) for binary in binary_array]
    print(key)
    
    showChart(key)
    # data = key
    # # 计算概率分布
    # counts, bins = np.histogram(data, bins=1000)
    # probs = counts / sum(counts) * 100

    # # 绘制概率分布图
    # plt.bar(bins[:-1], probs, width=0.001, alpha=0.7)

    # # 添加标题和标签
    # plt.title('chaos_Probability Distribution of Data')
    # plt.xlabel('Value')
    # plt.ylabel('Probability (%)')

    # # 显示图像
    # plt.show()  
